
//
// 120329 - AH - (Midtun) Created.
// 120403 - AH - Upload to Rat Base directory.
// 120713a- AH - Removed commented away code.
// 120713b- AH - Took RAT_BASE_NAME, SOEKRAT and SPARE in use.
//

package org.soekrat.server.servlets.file;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.japril.servlet.HttpRequestDef;
import org.soekrat.server.io.db.DbFile;
import org.soekrat.server.io.db.Folder;
import org.soekrat.server.io.db.SoekratDAO;
import org.soekrat.server.io.db.SoekratDAOFactory;
import org.soekrat.server.serialization.RatDataBaseSerializable;
import org.soekrat.server.servlets.AbstractSoekratHttpServlet;

/**
 * <p>
 *   Implements the request to upload the XML files defining a Soekrat
 *   database organized as a Soekrat data base online.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
@SuppressWarnings("serial")
public final class UploadRatBaseHttpServlet extends AbstractSoekratHttpServlet 
{
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public UploadRatBaseHttpServlet(){}

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    HttpRequestDef def=getHttpRequestDef();
    PrintWriter pw=printSimpleHtmlStart(res, "Upload a rat base");
    pw.println(def.compileApiHtml());
    printSimpleHtmlEnd(pw);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    handleRequest(req, res);
  }

  @Override
  protected void handleRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    try 
    {
      // Create a new file upload handler
      ServletFileUpload upload=new ServletFileUpload();
      
      Map<String, String> fp=new HashMap<String, String>();
      
      Map<String, byte[]> dataMap=new HashMap<String, byte[]>();
      
      // Parse the request
      FileItemIterator iter=upload.getItemIterator(req);
      while (iter.hasNext()) 
      {
        FileItemStream item=iter.next();
        
        InputStream is=item.openStream();
        
        if (item.isFormField()) 
        {
          String fname=item.getFieldName();
          String value=Streams.asString(is);
          
          value=(value==null) ? "" : value.trim();
          value=(value.length()==0) ? null : value;
          
          if (value!=null) fp.put(fname, value);
        }
        else
        {
          String fname=item.getName();
          
          byte[] data=readBytes(is);
          dataMap.put(fname, data);
        }
      }
      
      if (dataMap.isEmpty())
      {
        respond(res, "No data loaded");
        return;
      }
      if (dataMap.size()!=2)
      {
        respond(res, "Expected two files; got: "+dataMap.size());
        return;
      }
      
      byte[] soekratBytes=dataMap.get("soekrat.xml");
      byte[] spareBytes=dataMap.get("spare.xml");
      
      if (soekratBytes==null)
      {
        respond(res, "Did not get soekrat.xml");
        return;
      }
      if (spareBytes==null)
      {
        respond(res, "Did not get spare.xml");
        return;
      }
      
      SoekratDAO dao=new SoekratDAOFactory().create();
      
      String name=fp.get(RAT_BASE_NAME.name());
      if (name==null)
      {
        respond(res, "Missing data base name");
        return;
      }
      
      List<Folder> ratRoots=dao.getFolders(-1, "Rat Bases");
      if (ratRoots.isEmpty())
      {
        respond(res, "no root for rat bases found");
        return;
      }
      
      Folder ratRoot=ratRoots.get(0);
   
      Folder folder=dao.createFolder(name, ratRoot.id(), null);
      
      @SuppressWarnings("unused")
      DbFile wfile=dao.createFile("soekrat", folder.id(), soekratBytes, true, 
        "text/xml", -1, "Wheel XML");
      
      @SuppressWarnings("unused")
      DbFile sfile=dao.createFile("spare", folder.id(), spareBytes, true, 
        "text/xml", -1, "Spare wheel XML");
      
      respond(res, 
        new RatDataBaseSerializable().name(name).ratBaseId(folder.id()));
    } 
    catch (FileUploadException e)
    {
      throw new ServletException("Cannot parse multipart request.", e);
    }
  }
  
  @Override
  public HttpRequestDef getHttpRequestDef() 
  {
    return new HttpRequestDef(true, "rat_base_upload")
      .enctype("multipart/form-data").parameter(RAT_BASE_NAME)
      .parameter(SOEKRAT).parameter(SPARE);
  }
  
}
